import { useState, useEffect, useRef } from 'react';
import TodayDate from '../../../components/TodayDate/TodayDate';
import Calendar from '../../../components/Calendar/Calendar';
import WorkbenchEchart from '../../../components/WorkbenchEchart/WorkbenchEchart';
import WorkItem from '../../../components/WorkItem/WorkItem';
import ScrollButton from '../../../components/ScrollButton/ScrollButton';
import PosterItem from '../../../components/TemplateItem/PosterItem';
import LongPageItem from '../../../components/TemplateItem/LongPageItem';
import VideoItem from '../../../components/TemplateItem/VideoItem';
import { DirectTrainData, weeklydata, pieData, lineData, worksData, TemplateData } from './homeData';
import './home.css';

const Home = () => {
    // 日历
    const [visible, setVisible] = useState(false);

    // 数据tab切换
    const [activeTab, setActiveTab] = useState<string>('作品数据');
    const [activeSubTab, setActiveSubTab] = useState<string>('我参与的');
    const [hoverTab, setHoverTab] = useState<string | null>(null);
    const [hoverSubTab, setHoverSubTab] = useState<string | null>(null);
    const [timeoutId, setTimeoutId] = useState<NodeJS.Timeout | null>(null);

    // 定义 Tab 切换的处理函数
    const handleTabClick = (tabName: string) => {
        setActiveTab(tabName);
        setActiveSubTab('我参与的');
        clearTimeout(timeoutId!);
    };

    const handleSubTabClick = (subTabName: string) => {
        setActiveSubTab(subTabName);
    };

    const handleMouseEnter = (tabName: string) => {
        setHoverTab(tabName);
        const id = setTimeout(() => {
            setActiveTab(tabName);
        }, 1000);
        setTimeoutId(id);
    };

    const handleMouseLeave = () => {
        setHoverTab(null);
        if (timeoutId) {
            clearTimeout(timeoutId);
        }
    };

    useEffect(() => {
        return () => {
            if (timeoutId) {
                clearTimeout(timeoutId);
            }
        };
    }, [timeoutId]);

    const [activeItem, setActiveItem] = useState('全部');
    const [hoveredItem, setHoveredItem] = useState<string | null>(null);
    const items = ['全部', 'H5', '海报', '长页', '表单', '互动', '电子画册', '视频'];
    const filteredWorks = worksData.filter(work => activeItem === '全部' || work.category === activeItem);

    // 作品滚动控制
    const scrollRef = useRef<HTMLDivElement>(null);
    const [showLeftButton, setShowLeftButton] = useState(false);
    const [showRightButton, setShowRightButton] = useState(true);

    const scrollLeft = () => {
        if (scrollRef.current) {
            scrollRef.current.scrollBy({ left: -600, behavior: 'smooth' });
        }
    };

    const scrollRight = () => {
        if (scrollRef.current) {
            scrollRef.current.scrollBy({ left: 600, behavior: 'smooth' });
        }
    };

    const updateButtonVisibility = () => {
        if (scrollRef.current) {
            const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current;
            setShowLeftButton(scrollLeft > 0);
            setShowRightButton(scrollLeft < scrollWidth - clientWidth);
        }
    };

    useEffect(() => {
        const container = scrollRef.current;
        if (container) {
            container.addEventListener('scroll', updateButtonVisibility);
            updateButtonVisibility();
        }

        return () => {
            if (container) {
                container.removeEventListener('scroll', updateButtonVisibility);
            }
        };
    }, []);

    // 模版滚动控制
    const templateScrollRef = useRef<HTMLDivElement>(null);
    const [showTemplateLeftButton, setShowTemplateLeftButton] = useState(false);
    const [showTemplateRightButton, setShowTemplateRightButton] = useState(true);

    const scrollTemplateLeft = () => {
        if (templateScrollRef.current) {
            templateScrollRef.current.scrollBy({ left: -600, behavior: 'smooth' });
        }
    };

    const scrollTemplateRight = () => {
        if (templateScrollRef.current) {
            templateScrollRef.current.scrollBy({ left: 600, behavior: 'smooth' });
        }
    };

    const updateTemplateButtonVisibility = () => {
        if (templateScrollRef.current) {
            const { scrollLeft, scrollWidth, clientWidth } = templateScrollRef.current;
            setShowTemplateLeftButton(scrollLeft > 0);
            setShowTemplateRightButton(scrollLeft < scrollWidth - clientWidth);
        }
    };

    useEffect(() => {
        const container = templateScrollRef.current;
        if (container) {
            container.addEventListener('scroll', updateTemplateButtonVisibility);
            updateTemplateButtonVisibility();
        }

        return () => {
            if (container) {
                container.removeEventListener('scroll', updateTemplateButtonVisibility);
            }
        };
    }, []);

    return (
        <div className='home_box'>
            <div className='home_nei'>
                {/* 个人信息+日历 */}
                <div className='home_top'>
                    <div className='home_top_left'>
                        <div className="membership-offer-container">
                            <div className="checkbox-and-title">
                                <p className="title">待在门外</p>
                            </div>
                            <div className="price-info">
                                <p>低至<span className="price">3.8</span>元/天</p>
                                <button className="primary-button">开通会员</button>
                            </div>
                            <div className="button-group">
                                <p className="description">开通会员，全场模板免费用</p>
                                <p className="secondary">查看会员特权</p>
                            </div>
                        </div>
                    </div>
                    <div className='home_top_right'>
                        <div className='home_top_right1'
                            onMouseEnter={() => setVisible(true)}
                            onMouseLeave={() => setVisible(false)}
                        >
                            <div className='home_top_right1_date'>
                                <TodayDate />
                            </div>
                            <div className='home_top_right1_festival'>
                                <h3>世界旅游日</h3>
                            </div>

                            {visible && (
                                <div className='popup'>
                                    <div className='calendar-popup'>
                                        <Calendar />
                                    </div>
                                    <div className='DirectTrain'>
                                        <h2>营销模版直通车</h2>
                                        {
                                            DirectTrainData.map((item, index) => {
                                                return (
                                                    <div key={index}>
                                                        <div className='DirectTrain_box'>
                                                            <p>{item.date}</p><p>剩<span className='DirectTrain_context'>{item.content}</span>天</p>
                                                        </div>
                                                        <h3 className='DirectTrain_url'>
                                                            <a href={item.url}>{item.title}</a>
                                                        </h3>
                                                    </div>
                                                );
                                            })
                                        }
                                    </div>
                                </div>
                            )}
                        </div>
                        <div className='home_top_right2'>
                            <p>【2024/9/20更新】喜迎国庆,大额立减券限时领</p>
                            <p>【一举两得】H5作品一键转视频,节日祝福传播更多样</p>
                        </div>
                    </div>
                </div>
                {/* 我的数据 */}
                <div className='home_data'>
                    <div className='home_data1'>
                        <h1 className='home_data1_h1'>我的数据</h1>
                        <ul className='home_data1_ul'>
                            <li
                                onClick={() => handleTabClick('作品数据')}
                                onMouseEnter={() => handleMouseEnter('作品数据')}
                                onMouseLeave={handleMouseLeave}
                                style={{ cursor: 'pointer', fontWeight: activeTab === '作品数据' || hoverTab === '作品数据' ? 'bold' : 'normal', color: activeTab === '作品数据' || hoverTab === '作品数据' ? '#1261ff' : 'inherit' }}
                            >
                                作品数据
                            </li>
                            <li
                                onClick={() => handleTabClick('分发数据')}
                                onMouseEnter={() => handleMouseEnter('分发数据')}
                                onMouseLeave={handleMouseLeave}
                                style={{ cursor: 'pointer', fontWeight: activeTab === '分发数据' || hoverTab === '分发数据' ? 'bold' : 'normal', color: activeTab === '分发数据' || hoverTab === '分发数据' ? '#1261ff' : 'inherit' }}
                            >
                                分发数据
                            </li>
                        </ul>
                        <div className='home_data1_more'>
                            <span className='home_data1_more_span'>查看更多</span>
                        </div>
                    </div>
                    <div className='home_data2'>
                        {activeTab === '作品数据' && (
                            <div className='home_data_workdata'>
                                <div className='home_data_workdata_left'>
                                    <div className='home_data_workdata_left_title'>
                                        <h3>活跃周报</h3>
                                        <p>9.16-9.22</p>
                                        <div>去制作</div>
                                    </div>
                                    <div className='home_data_workdata_left_center'>
                                        <div className='home_data_workdata_left_center1'>
                                            {
                                                weeklydata.map((item, index) => {
                                                    return (
                                                        <div key={index}>
                                                            <div>{item.num}</div>
                                                            <p className='home_data_workdata_left_center1_title'>{item.title}</p>
                                                            <p className='home_data_workdata_left_center1_contrast'><span>周对比</span> <span>{item.contrast}</span> </p>
                                                        </div>
                                                    );
                                                })
                                            }
                                        </div>
                                        <div className='home_data_workdata_left_center2'>
                                            <div className='home_data_workdata_left_center2_echart'>
                                                <WorkbenchEchart chartType="pie" data={{ seriesData: pieData }} chartId="pieChart" />
                                            </div>
                                            <div>制作数量</div>
                                        </div>
                                    </div>
                                </div>
                                <div className='home_data_workdata_right'>
                                    <div className='home_data_workdata_right_title'>
                                        <h3>数据分析</h3>
                                    </div>
                                    <div className='home_data_workdata_right_echart'>
                                        <WorkbenchEchart chartType="line" data={lineData} chartId="lineChart" />
                                    </div>
                                </div>
                            </div>
                        )}
                        {activeTab === '分发数据' && (
                            <div>
                                <div className='home_data_distributedata_tab'>
                                    <ul>
                                        <li
                                            onMouseEnter={() => setHoverSubTab('我发起的')}
                                            onMouseLeave={() => setHoverSubTab(null)}
                                            onClick={() => handleSubTabClick('我发起的')}
                                            style={{
                                                cursor: 'pointer',
                                                backgroundColor: activeSubTab === '我发起的' ? '#1261ff' : 'transparent',
                                                color: activeSubTab === '我发起的' ? 'white' : hoverSubTab === '我发起的' ? '#1261ff' : 'inherit',
                                                border: hoverSubTab === '我发起的' ? '1px solid #1261ff' : 'none',
                                                borderRadius: hoverSubTab === '我发起的' ? '4px' : '0',
                                            }}
                                        >
                                            我发起的
                                        </li>
                                        <li
                                            onMouseEnter={() => setHoverSubTab('我参与的')}
                                            onMouseLeave={() => setHoverSubTab(null)}
                                            onClick={() => handleSubTabClick('我参与的')}
                                            style={{
                                                cursor: 'pointer',
                                                backgroundColor: activeSubTab === '我参与的' ? '#1261ff' : 'transparent',
                                                color: activeSubTab === '我参与的' ? 'white' : hoverSubTab === '我参与的' ? '#1261ff' : 'inherit',
                                                border: hoverSubTab === '我参与的' ? '1px solid #1261ff' : 'none',
                                                borderRadius: hoverSubTab === '我参与的' ? '4px' : '0',
                                            }}
                                        >
                                            我参与的
                                        </li>
                                    </ul>
                                </div>
                                <div className='home_data_distributedata_center'>
                                    {activeSubTab === '我参与的' && (
                                        <div>
                                            <div className='home_data_distributedata_center_img'>
                                                <img src="https://www.eqxiu.com/workbench/img/empty.143a1468.png" alt="" />
                                            </div>
                                            <div className='home_data_distributedata_center_title'>
                                                还没有参与作品分发
                                            </div>
                                        </div>
                                    )}
                                    {activeSubTab === '我发起的' && (
                                        <div>
                                            <div className='home_data_distributedata_center_img'>
                                                <img src="https://www.eqxiu.com/workbench/img/empty.143a1468.png" alt="" />
                                            </div>
                                            <div className='home_data_distributedata_center_title'>
                                                当前暂无团队，快去创建吧
                                            </div>
                                            <div className='home_data_distributedata_center_buttom'>
                                                <button>创建</button>
                                            </div>
                                        </div>
                                    )}
                                </div>
                            </div>
                        )}
                    </div>
                </div>
                {/* 作品 */}
                <div className='home_works'>
                    <div className='home_works_title'>
                        <h1>作品</h1>
                        <div><span>查看更多</span></div>
                    </div>
                    <div className='home_works_tab'>
                        <ul>
                            {items.map(item => (
                                <li
                                    key={item}
                                    onMouseEnter={() => setHoveredItem(item)}
                                    onMouseLeave={() => setHoveredItem(null)}
                                    onClick={() => setActiveItem(item)}
                                    style={{
                                        cursor: 'pointer',
                                        backgroundColor: activeItem === item ? '#1261ff' : 'transparent',
                                        color: activeItem === item ? 'white' : hoveredItem === item ? '#1261ff' : 'black',
                                        border: hoveredItem === item ? '1px solid #1261ff' : '1px solid #e6ebed',
                                        borderRadius: '4px',
                                        padding: '0px 10px',
                                        margin: '5px 0'
                                    }}
                                >
                                    {item}
                                </li>
                            ))}
                        </ul>
                    </div>
                    <div className='home_works_container'>
                        {/* 滚动按钮 */}
                        <ScrollButton direction="left" onClick={scrollLeft} visible={showLeftButton} />
                        <div className='home_works_center' ref={scrollRef}>
                            {filteredWorks.length === 0 ? (
                                <div className='home_works_center_null'>
                                    <div className='home_data_distributedata_center_img'>
                                        <img src="https://www.eqxiu.com/workbench/img/empty.143a1468.png" alt="" />
                                    </div>
                                    <div className='home_data_distributedata_center_title'>
                                        你的作品列表为空，快去创建吧
                                    </div>
                                    <div className='home_data_distributedata_center_buttom'>
                                        <button className='home_data_distributedata_center_ckbuttom'>查看新手教程</button>
                                        <button>创建</button>
                                    </div>
                                </div>
                            ) : (
                                filteredWorks.map((work, index) => (
                                    <WorkItem key={index} {...work} />
                                ))
                            )}
                        </div>
                        <ScrollButton direction="right" onClick={scrollRight} visible={showRightButton} />
                    </div>
                </div>
                {/* 精选模版 */}
                <div className='home_template'>
                    <div className='home_works_title'>
                        <h1>精选模版</h1>
                        <div><span>查看更多</span></div>
                    </div>
                    <div className='home_template_container'>
                        {/* 滚动按钮 */}
                        <ScrollButton
                            direction="left"
                            onClick={scrollTemplateLeft}
                            visible={showTemplateLeftButton}
                        />
                        <div className='home_template_center' ref={templateScrollRef}>
                            {TemplateData.map((item, index) => {
                                switch (item.type) {
                                    case '海报':
                                        return (
                                            <PosterItem
                                                key={index}
                                                title={item.title}
                                                name={item.name}
                                                number={item.number}
                                                images={item.images}
                                                type={item.type}
                                            />
                                        );
                                    case '长页':
                                        return (
                                            <LongPageItem
                                                key={index}
                                                title={item.title}
                                                name={item.name}
                                                number={item.number}
                                                imageUrl={item.url}
                                                type={item.type}
                                            />
                                        );
                                    case '视频':
                                        return (
                                            <VideoItem
                                                key={index}
                                                title={item.title}
                                                name={item.name}
                                                number={item.number}
                                                videoUrl={item.url}
                                                type={item.type}
                                            />
                                        );
                                    default:
                                        return null;
                                }
                            })}
                        </div>
                        <ScrollButton
                            direction="right"
                            onClick={scrollTemplateRight}
                            visible={showTemplateRightButton}
                        />
                    </div>
                </div>
            </div>
        </div>
    );
}

export default Home;
